<template>
  <div class="header">
    <!-- 左侧标题 -->
    <div class="header-left">
      <icons class="icon-menu" name="menu" @click="openDrawer" />
      <div class="title">
        <div class="title-view" v-if="token">
          <span v-if="systemInfo.systemName" @click="toPage('/')">{{
            systemInfo.systemName
          }}</span>
          <span v-else class="txt" @click="setSettingDialog">编辑系统名称</span>
          <div v-if="store.superUser < 2" @click="setSettingDialog">
            <icons class="edit-icon" name="editIcon" />
          </div>
        </div>
        <div v-else>账户登录</div>
      </div>
      <div class="sub-title">{{ name }}</div>
    </div>
    <!-- 右侧LOGO -->
    <div
      v-if="!logoInfo.logoParamas.content && token && store.superUser < 2"
      class="header-right"
      @click="clickLogo"
    >
      <icons class="edit-icon" name="editIcon" />
      <span>编辑LOGO</span>
    </div>
    <!-- 文字 -->
    <div
      v-if="logoInfo.logoParamas.content && token"
      class="right-txt"
      @click="clickLogo"
    >
      <img
        v-if="logoInfo.logoParamas.type === 'picture'"
        class="log-img"
        :src="logoInfo.logoParamas.content"
        alt=""
      />
      <div v-else class="log-text">{{ logoInfo.logoParamas.content }}</div>
    </div>
  </div>
  <!-- 编辑LOGO -->
  <LogoEdit
    :showModal="showModal"
    :dialogTitle="LogoTitle"
    @closeModel="closeLogoDialog"
    class="demo"
  >
    <div class="logo-dialog">
      <div class="radio-box">
        <n-radio
          :checked="logoParamas.type === 'picture'"
          value="picture"
          name="basic-demo"
          :default-checked="true"
          @change="handleChange"
        >
          单独图片
        </n-radio>
        <n-radio
          style="margin-left: 60px; color: #1677ff"
          :checked="logoParamas.type === 'text'"
          value="text"
          name="basic-demo"
          @change="handleChange"
        >
          单独文字
        </n-radio>
      </div>
      <!-- 图片上传 -->
      <div class="img-upload" v-if="logoParamas.type === 'picture'">
        <div class="header-title">图片上传</div>
        <div class="upload-box">
          <n-upload
            list-type="image-card"
            :default-file-list="previewFileList"
            :custom-request="customRequest"
            accept="image/png, image/jpeg,image/webp"
            :max="1"
          >
            点击上传
          </n-upload>
        </div>
        <div class="desc">建议上传尺寸90*90</div>
      </div>
      <!-- 文字 -->
      <div class="img-upload" v-else>
        <div class="header-title">LOGO文字</div>
        <div class="upload-box">
          <n-input
            maxlength="50"
            v-model:value="logoTxt"
            type="text"
            placeholder="请输入LOGO文字"
          />
        </div>
      </div>
      <div class="pop-btn-view" @click="subMit">保存</div>
    </div>
  </LogoEdit>
  <!-- 侧边抽屉 -->
  <Drawer />
</template>
<script lang="ts" setup>
import { ref, watch, computed, reactive, onMounted } from "vue";
import LogoEdit from "@/components/Dialog/index.vue";
import Drawer from "@/components/Sidebar/index.vue";
import { useAppStore } from "@/store/modules/user";
import { tmpStore } from "@/store/modules/template";
import { uuid } from "@/tools/radom";
import { useRouter, useRoute } from "vue-router";
import { UploadCustomRequestOptions } from "naive-ui";
import {
  GetLogo,
  InsertOrUpdateLogo,
  UploadFile,
  GetSystemFont,
  GetPageModelByToken,
} from "@/server";
const router = useRouter();
const route = useRoute();
const name = computed(() => route.params.type || route.meta.title);
const template = tmpStore();
const store = useAppStore();
const logoTxt = ref(""); //文字logo
const logoImg = ref(""); //图片logo
const showModal = ref(false); //展示弹窗
const systemInfo = computed(() => template.systemData);
const token = computed(() => store.token);
const showDrawer = computed(() => store.showDrawer);
const userInfo = computed(() => store.userInfo);
//系统设置
//是否打开系统设置弹窗
const setSettingDialog = () => {
  if (store.superUser < 2) {
    template.openSysPop(true);
  }
};

const logoInfo = reactive({
  logoParamas: {
    type: "picture", //picture/text
    content: "", //logo内容
    font: "", //字体
    size: "", //字体大小
    color: "", //字体颜色
    isBold: false, //是否粗体
    companyId: 1,
  },
});
const logoParamas = ref(null) as any;
/**
 * @description: 获取模版信息
 * @return {*}
 * @author: cool panda
 */
const GetPageModelByTokenFun = async () => {
  const res: any = await GetPageModelByToken({});
  if (res.result.isSuccess) {
    template.setMnue(res.result.result);
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const previewFileList = ref([]) as any; //logo
const customRequest = async ({
  file,
  onFinish,
  onError,
  onProgress,
}: UploadCustomRequestOptions) => {
  const formData = new FormData();
  if (file && file.type) {
    const fileName = file.name;
    const fileExtension = fileName.split(".").pop();
    const randomSuffix = uuid();
    // 构建新文件名
    const newFileName = `${randomSuffix}.${fileExtension}`;
    // 创建一个新的File对象，用新文件名替换原文件名
    formData.append("file", file.file as File, newFileName);
    // 创建一个新Blob对象，将文件内容复制到其中
    onProgress({ percent: 10 });
    const res: any = await UploadFile(formData);
    if (res.result.isSuccess) {
      onProgress({ percent: 100 });
      const imgUrl = res.result.result.fileName; //图片上传的路径
      logoImg.value = imgUrl;
      setTimeout(() => {
        onFinish();
      }, 500);
    } else {
      onError();
      store.error(res.result.message); // 错误提示
    }
  }
};
const toPage = (url: string) => {
  router.push(url);
};
//打开侧边栏
const openDrawer = () => {
  store.openMenu(!showDrawer.value);
};
//点击编辑LOGO
const clickLogo = () => {
  if (store.superUser < 2) {
    logoParamas.value = JSON.parse(JSON.stringify(logoInfo.logoParamas));
    showModal.value = true;
  }
};
//关闭LOGO弹框
const closeLogoDialog = (val: boolean) => {
  showModal.value = val;
  if (!val) {
    logoTxt.value = "";
    logoImg.value = "";
  }
};
const subMit = async () => {
  logoParamas.value.companyId = userInfo.value.companyId;
  logoParamas.value.content =
    logoParamas.value.type === "picture" ? logoImg.value : logoTxt.value;
  if (!logoParamas.value.content) {
    store.warning("内容不能为空");
    return false;
  }
  const res: any = await InsertOrUpdateLogo(logoParamas.value);
  if (res.result.isSuccess) {
    getLogoFun();
    store.success("保存成功"); // 错误提示
    showModal.value = false;
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取logo
const getLogoFun = async () => {
  const res: any = await GetLogo({});
  if (res.result.isSuccess) {
    logoInfo.logoParamas = res.result.result;
    if (logoInfo.logoParamas.type === "string" || !logoInfo.logoParamas.type) {
      logoInfo.logoParamas.type = "text";
    }
    if (logoInfo.logoParamas.type === "picture") {
      logoTxt.value = "";
      logoImg.value = logoInfo.logoParamas.content;
      previewFileList.value = [
        {
          id: "1",
          name: "",
          status: "finished",
          url: logoImg.value,
        },
      ];
    } else {
      previewFileList.value = [];
      logoTxt.value = logoInfo.logoParamas.content;
    }
  } else {
    // store.error(res.result.message); // 错误提示
  }
};
//获取系统设置信息
const getSystemFontFun = async () => {
  const res: any = await GetSystemFont({ Token: "" });
  if (res.result.isSuccess) {
    template.setSystemInfo(res.result.result);
  } else {
    // store.error(res.result.message); // 错误提示
  }
};
//LOGO弹框标题
const LogoTitle = ref("编辑LOGO");
//单选按钮
const handleChange = (e: Event) => {
  logoParamas.value.type = (e.target as HTMLInputElement).value;
};
//token变动重新获取数据
watch(
  () => token.value,
  (val) => {
    if (val) {
      GetPageModelByTokenFun();
      getLogoFun();
      getSystemFontFun();
    } else {
      logoInfo.logoParamas = {
        type: "picture", //picture/text
        content: "", //logo内容
        font: "", //字体
        size: "", //字体大小
        color: "", //字体颜色
        isBold: false, //是否粗体
        companyId: 1,
      };
      template.setSystemInfo(null);
      template.setMnue([]);
      store.setUserInfo(null);
    }
  }
);
</script>
<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 40px 0 30px;
  height: 88px;
  color: #ffffff;

  .header-left {
    display: flex;
    align-items: center;

    .icon-menu {
      width: 35px;
      height: 28px;
    }

    .title {
      cursor: pointer;
      display: flex;
      margin-left: 20px;
      font-size: 22px;
      .title-view {
        display: flex;
      }

      // color: #fff;
      .edit-icon {
        margin-left: 5px;
      }
    }
    .sub-title {
      margin-left: 50px;
      font-size: 21px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: rgba(255, 255, 255, 0.85);
      line-height: 32px;
    }
  }

  .header-right {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 113px;
    height: 70px;
    // color: #fff;
    background-color: #394248;

    .edit-icon {
      width: 30px;
      height: 30px;
      margin: 5px 0;
    }
  }
  .right-txt {
    min-width: 30px;
    height: 30px;
    cursor: pointer;
    .log-img {
      height: 30px;
      object-fit: contain;
    }
    .log-text {
      font-size: 24px;
      font-family: SourceHanSansCN-Bold, SourceHanSansCN;
      font-weight: bold;
      color: #ffffff;
      line-height: 36px;
    }
  }
}

.logo-dialog {
  height: 320px;
  // color: #fff;
  :deep(.n-radio__label) {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    line-height: 22px;
  }
  //图片上传
  .img-upload {
    display: flex;
    flex-direction: column;
    margin-top: 30px;
    height: 150px;

    .header-title {
      font-size: 16px;
      // color: #fff;
      margin-bottom: 15px;
    }
    .upload-box {
      .n-upload {
        --n-dragger-color: none !important;
      }
    }
    .desc {
      margin-top: 5px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #d8d8d8;
      line-height: 17px;
    }
  }
  .pop-btn-view {
    cursor: pointer;
    margin: 50px auto 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100px;
    height: 36px;
    background: #01c0e4;
    box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.08),
      0px 2px 5px 0px rgba(25, 15, 15, 0.07),
      0px 5px 8px 0px rgba(0, 0, 0, 0.05);
  }
}
</style>
